package com.vmj.heap;

/**
 * Created by yangshoujun on 2017/9/9 上午12:52.
 */
public class ArrayObject {

    public static byte[] getBytes(VMObject obj) {
        return (byte[]) obj.data;
    }

    public static short[] getShorts(VMObject obj) {
        return (short[]) obj.data;
    }

    public static int[] getInts(VMObject obj) {
        return (int[]) obj.data;
    }

    public static long[] getLongs(VMObject obj) {
        return (long[]) obj.data;
    }

    public static double[] getDoubles(VMObject obj) {
        return (double[]) obj.data;
    }

    public static float[] getFloats(VMObject obj) {
        return (float[]) obj.data;
    }

    public static VMObject[] getRefs(VMObject obj) {
        return (VMObject[]) obj.data;
    }

    public static char[] getChars(VMObject obj) {
        return (char[]) obj.data;
    }

    public static int getArrayLength(VMObject obj) {
        if(obj.data instanceof byte[]) {
            return ((byte[])(obj.data)).length;
        } else if(obj.data instanceof short[]) {
            return ((short[])(obj.data)).length;
        } else if(obj.data instanceof double[]) {
            return ((double[])(obj.data)).length;
        } else if(obj.data instanceof char[]) {
            return ((char[])(obj.data)).length;
        } else if(obj.data instanceof int[]) {
            return ((int[])(obj.data)).length;
        } else if(obj.data instanceof float[]) {
            return ((float[])(obj.data)).length;
        } else if(obj.data instanceof long[]) {
            return ((long[])(obj.data)).length;
        } else if(obj.data instanceof VMObject[]) {
            return ((VMObject[])(obj.data)).length;
        } else {
            throw new RuntimeException("Invalid array type: " + obj.getClazz());
        }
    }

    public static VMObject newMultiDemensionalArray(int[] counts, VMClass clazz) {
        int count = counts[0];
        VMObject arr = VMObject.newArray(clazz, count);
        if(counts.length > 1) {
            VMObject[] refs = ArrayObject.getRefs(arr);
            for(int i = 0; i < refs.length;i++) {
                int[] inner = new int[counts.length - 1];
                System.arraycopy(counts, 1, inner, 0, counts.length - 1);
                refs[i] = newMultiDemensionalArray(inner, clazz.getComponentClass());
            }
        }
        return arr;
    }

    public static VMObject newByteArray(ClassLoader classLoader, byte[] data) {
        VMClass clazz = classLoader.loadClass("[B");
        VMObject obj = clazz.newObject();
        obj.setData(data);
        obj.setExtra(null);
        return obj;
    }

}
